<template>
  <div class="jsbos-common-layout">
    <div class="jsbos-common-layout-center">
      <el-row class="jsbos-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="4">
            <el-form-item label="名称">
              <el-input
                v-model="query.name"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="分类">
              <el-select
                v-model="query.categoryId"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) in categoryIdOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.enCode"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="有效期">
              <el-select
                v-model="query.expiredType"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) in expiredTypeOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="4">
              <el-form-item label="有效标志">
                <el-select
                  v-model="query.enabledMark"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in enabledMarkOptions"
                    :key="index"
                    :label="item.fullName"
                    :value="item.id"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="4">
            <el-form-item label="">
              <el-checkbox
                v-model="query.myCreated"
                @change="
                  query.myCreated
                    ? (query.creatorUserId = userInfo.userId)
                    : (query.creatorUserId = '');
                  search();
                "
                >只看我创建的</el-checkbox
              >
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
              <el-button
                type="text"
                icon="el-icon-arrow-down"
                @click="showAll = true"
                v-if="!showAll"
              >
                展开
              </el-button>
              <el-button
                type="text"
                icon="el-icon-arrow-up"
                @click="showAll = false"
                v-else
              >
                收起
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="jsbos-common-layout-main jsbos-flex-main">
        <div class="jsbos-common-head">
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addOrUpdateHandle()"
              >新增
            </el-button>
          </div>
          <div class="jsbos-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JSBOS-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <screen-full isContainer />
            <el-tooltip effect="dark" content="列设置" placement="top">
              <el-link
                icon="icon-ym icon-ym-options jsbos-common-head-icon"
                :underline="false"
                @click="() => this.$refs.jsbosTableRef.showDrawer()"
              />
            </el-tooltip>
          </div>
        </div>
        <jsbos-table
          v-loading="listLoading"
          :data="list"
          ref="jsbosTableRef"
          @sort-change="sortChange"
        >
          <el-table-column prop="name" label="名称" width="0" align="left">
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="goDetail(scope.row.id)"
                >{{ scope.row.name }}</el-link
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="categoryId"
            label="分类"
            width="0"
            align="left"
          >
            <template slot-scope="scope">
              {{ scope.row.categoryId | dynamicText(categoryIdOptions) }}
            </template>
          </el-table-column>
          <el-table-column
            label="有效期"
            width="0"
            prop="expiredType"
            algin="left"
          >
            <template slot-scope="scope">
              {{ scope.row.expiredType | dynamicText(expiredTypeOptions) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="expiredDay"
            label="有效期时长"
            width="0"
            align="left"
          />
          <el-table-column
            prop="creatorUserId"
            label="创建用户"
            width="0"
            align="left"
          />
          <el-table-column
            prop="creatorTime"
            label="创建时间"
            width="0"
            align="left"
          />
          <el-table-column
            label="有效标志"
            width="0"
            prop="enabledMark"
            algin="center"
          >
            <template slot-scope="scope">
              {{ scope.row.enabledMark | dynamicText(enabledMarkOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" @click="goDataDetail(scope.row.id)"
                >数据
              </el-button>
              <el-button type="text" @click="goDetail(scope.row.id)"
                >详情
              </el-button>
              <el-dropdown>
                <span class="el-dropdown-link">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-if="scope.row.enabledMark == 1"
                    @click.native="handleIssueCertOpen(scope.row.id)"
                    >颁发证书</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="scope.row.enabledMark == 1"
                    @click.native="handleUnpublish(scope.row.id)"
                    >取消发布</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="scope.row.enabledMark == 0"
                    @click.native="addOrUpdateHandle(scope.row.id)"
                    >编辑</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="scope.row.enabledMark == 0"
                    @click.native="handleDel(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </jsbos-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <JSBOS-Form v-if="formVisible" ref="JSBOSForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <Detail
      v-if="detailVisible"
      ref="Detail"
      @refresh="detailVisible = false"
    />
    <CertUserData
      v-if="dataVisible"
      ref="CertUserData"
      @refresh="dataVisible = false"
    />
    <user-select
      v-show="false"
      ref="userSelect"
      v-model="issuedCertList"
      @change="handleIssueCert"
      :multiple="userSelectMultiple"
      placeholder="请选择"
      clearable
    >
    </user-select>
  </div>
</template>

<script>
import request from "@/utils/request";
import JSBOSForm from "./Form.vue";
import ExportBox from "./ExportBox.vue";
import { getDataInterfaceRes } from "@/api/systemData/dataInterface";
import Detail from "./Detail.vue";
import CertUserData from "./CertUserData.vue";
import { mapGetters } from "vuex";

export default {
  name: "TemsCert",
  components: { JSBOSForm, ExportBox, Detail, CertUserData },
  data() {
    return {
      userSelectMultiple: true,
      showAll: false,
      detailVisible: false,
      dataVisible: false,
      issueCertId: "",
      query: {
        name: undefined,
        categoryId: undefined,
        expiredType: undefined,
        creatorUserId: undefined,
        enabledMark: undefined,
        myCreated: false,
      },
      treeProps: {
        children: "children",
        label: "fullName",
        value: "id",
      },
      issuedCertList: [],
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      },
      formVisible: false,
      exportBoxVisible: false,
      columnList: [
        { prop: "name", label: "名称" },
        { prop: "categoryId", label: "分类" },
        { prop: "expiredType", label: "有效期" },
        { prop: "expiredDay", label: "有效期时长" },
        { prop: "creatorUserId", label: "创建用户" },
        { prop: "creatorTime", label: "创建时间" },
        { prop: "enabledMark", label: "有效标志" },
      ],
      categoryIdOptions: [],
      categoryIdProps: {
        label: "fullName",
        value: "enCode",
      },
      expiredTypeOptions: [
        { fullName: "永久有效", id: "1" },
        { fullName: "有效周期", id: "2" },
      ],
      expiredTypeProps: {
        label: "fullName",
        value: "id",
      },
      enabledMarkOptions: [
        { fullName: "待发布", id: "0" },
        { fullName: "已发布", id: "1" },
      ],
      enabledMarkProps: {
        label: "fullName",
        value: "id",
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    menuId() {
      return this.$route.meta.modelId || "";
    },
  },
  created() {
    this.initData();
    this.getCategoryIdOptions();
  },
  methods: {
    getCategoryIdOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "CertificateCategory",
        })
        .then((res) => {
          this.categoryIdOptions = res;
        });
    },
    goDetail(id) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id);
      });
    },
    goDataDetail(id) {
      this.dataVisible = true;
      this.$nextTick(() => {
        this.$refs.CertUserData.init(id);
      });
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/course/TemsCert/getList`,
        method: "post",
        data: _query,
      }).then((res) => {
        var _list = [];
        for (let i = 0; i < res.data.list.length; i++) {
          let _data = res.data.list[i];
          _list.push(_data);
        }
        this.list = _list;
        this.total = res.data.pagination.total;

        this.listLoading = false;
      });
    },
    handleIssueCertOpen(id) {
      this.issueCertId = id;
      this.$refs.userSelect.openDialog();
    },
    handleIssueCert(ids, data) {
      console.log(ids, "===========", data);
      if (ids.length >= 0) {
        let _data = {
          certId: this.issueCertId,
          certUserIds: ids,
        };
        request({
          url: "/api/course/TemsCertUser/issueCert",
          method: "post",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      }
    },
    handleUnpublish(id) {
      this.$confirm(
        "取消发布后学员在证书界面将看不到当前证书了，确定要取消发布吗？",
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          request({
            url: `/api/course/TemsCert/unpublish/${id}`,
            method: "PUT",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      })
        .then(() => {
          request({
            url: `/api/course/TemsCert/${id}`,
            method: "DELETE",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JSBOSForm.init(id, isDetail);
      });
    },
    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList);
      });
    },
    download(data) {
      let query = {
        ...data,
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/course/TemsCert/Actions/Export`,
        method: "GET",
        data: query,
      }).then((res) => {
        if (!res.data.url) return;
        this.jsbos.downloadFile(res.data.url);
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      };
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.search();
    },
  },
};
</script>
<style lang="scss" scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
}
</style>
